<template>
  <div class="create-folder-container">
    <el-dialog
      v-model="dialogVisible"
      title="新建文件夹"
      width="400px"
      center
      :close-on-click-modal="false"
      destroy-on-close
    >
      <div class="folder-form">
        <el-form :model="formData" label-position="top" label-width="80px">
          <el-form-item label="创建位置">
            <el-input
              v-model="formData.currentPath"
              placeholder="当前路径"
              disabled
              size="large"
            />
          </el-form-item>
          
          <el-form-item label="文件夹名称" prop="folderName">
            <el-input
              v-model="formData.folderName"
              placeholder="请输入文件夹名称"
              size="large"
              ref="nameInput"
              @keyup.enter="handleConfirm"
            />
            <div class="error-message" v-if="errorMessage">{{ errorMessage }}</div>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="confirmLoading">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { asyncNewFolder } from '../api/fileManage.js'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  currentPath: {
    type: String,
    default: ''
  }
})

// Emits
const emit = defineEmits(['update:visible', 'create-success', 'create-fail'])

// 响应式数据
const dialogVisible = ref(false)
const confirmLoading = ref(false)
const nameInput = ref(null)
const errorMessage = ref('')
const formData = ref({
  currentPath: '',
  folderName: ''
})

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    dialogVisible.value = true
    initForm()
    nextTick(() => {
      if (nameInput.value) {
        nameInput.value.focus()
      }
    })
  } else {
    dialogVisible.value = false
  }
})

// 监听dialogVisible变化
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
  if (!newVal) {
    resetForm()
  }
})

// 监听currentPath变化
watch(() => props.currentPath, (newVal) => {
  if (dialogVisible.value) {
    formData.value.currentPath = newVal
  }
})

// 初始化表单
const initForm = () => {
  formData.value.currentPath = props.currentPath
  formData.value.folderName = ''
  errorMessage.value = ''
}

// 重置表单
const resetForm = () => {
  formData.value = {
    currentPath: '',
    folderName: ''
  }
  errorMessage.value = ''
  confirmLoading.value = false
}

// 验证表单
const validateForm = () => {
  const folderName = formData.value.folderName.trim()
  
  if (!folderName) {
    errorMessage.value = '请输入文件夹名称'
    return false
  }
  
  // 检查文件夹名是否包含特殊字符
  const invalidChars = /[\\/:*?"<>|]/g
  if (invalidChars.test(folderName)) {
    errorMessage.value = '文件夹名不能包含以下字符: \\ / : * ? " < > |'
    return false
  }
  
  // 检查文件夹名长度
  if (folderName.length > 255) {
    errorMessage.value = '文件夹名长度不能超过255个字符'
    return false
  }
  
  // 检查是否为保留名称
  const reservedNames = ['CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3', 'COM4', 
                         'COM5', 'COM6', 'COM7', 'COM8', 'COM9', 'LPT1', 'LPT2', 
                         'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9']
  
  if (reservedNames.includes(folderName.toUpperCase())) {
    errorMessage.value = `"${folderName}" 是保留名称，不能用作文件夹名`
    return false
  }
  
  errorMessage.value = ''
  return true
}

// 处理确认
const handleConfirm = async () => {
  if (!validateForm()) {
    nextTick(() => {
      if (nameInput.value) {
        nameInput.value.focus()
      }
    })
    return
  }
  
  confirmLoading.value = true
  
  try {
    const folderName = formData.value.folderName.trim()
    const paths = formData.value.currentPath
    
    const objs = {
      "name": folderName,
      "filetype": "0",
      "isParent": true,
      "new": true
    }
    
    // 添加响应数据检查
    const res = await asyncNewFolder("create", paths, folderName)
    
    // 检查响应结构
    if (!res) {
      throw new Error('API响应格式错误')
    }
    
    // 检查code字段
    if (res.code == 200) {
      ElMessage.success(res.msg || "操作成功")
      
      // 构建新文件夹数据
      const newFolder = {
        ...objs,
        id: res.data?.id || '',
        fid: res.data?.fid || '',
        path: paths,
        checked: false
      }
      
      emit('create-success', newFolder)
      dialogVisible.value = false
    } else {
      ElMessage.error(res.msg || '创建失败')
      emit('create-fail', new Error(res.msg || '创建失败'))
    }
  } catch (error) {
    console.error('创建文件夹失败:', error)
    ElMessage.error('操作失败')
    emit('create-fail', error)
  } finally {
    confirmLoading.value = false
  }
}

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.create-folder-container {
  font-size: 14px;
}

.folder-form {
  padding: 10px 0;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  margin-bottom: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
    max-width: 400px;
  }
}
</style>